<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="currency_cod"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :type="col.type"
                :sortable="col.sortable"
            >
                
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary"  @click="add"
            >增加</el-button
        >
        <el-button class="btn" type="primary"  @click="onDelete"
            >删除</el-button
        >
        <el-button class="btn" type="primary"  @click="onQuery"
            >查询</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="货币维护"
        draggable
        destroy-on-close
        :center="true"
    >
        <NormalSysForm
            :formOptions="formOptions"
            :formItems="formItems"
            :formData="paramData"
            :createActionName="createActionName"
            :updateActionName="updateActionName"
            :rules="rules"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </NormalSysForm>
    </el-dialog>
    <el-dialog
        v-model="dialogQueryVisible"
        title="货币查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="Currency">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElTable, FormRules } from 'element-plus';
// import { Delete, Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit,
} from 'lodash';

import NormalSysForm from '@/components/forms/NormalSysForm.vue'
import type { CurrencyModel } from '@/common/types/business';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { FormFieldItem, QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    initObjectProperty,
    pickFormFromTable,
    pickQueryFromTable,
} from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
import { useAppStore } from '@/store/app';
const appStore = useAppStore();
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<CurrencyModel>>([]);
const paramData = reactive<CurrencyModel>({});
const tableHeight = ref(100);
const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const rules = reactive<FormRules>({
    currency_cod: [
        { required: true, message: '请输入货币代码', trigger: 'blur' },
        { min:3, max: 3, message: '货币代码长度必须为3位', trigger: 'blur' },
    ],
    currency_nam: [
        { required: true, message: '请输入货币名称', trigger: 'blur' },
        { max: 60, message: '货币名称长度不能超过20位', trigger: 'blur' },
    ],
    rate: [
        { required: true, message: '请输入汇率', trigger: 'blur' },
    ],
});
const tableColumns = reactive<TableColumn[]>([
    
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'currency_cod',
        label: '货币代码',
        sortable: 'custom',
        formFieldItemType: 'input',
    },
    {
        ...tableColumnDefault,
        order:2,
        prop: 'currency_nam',
        label: '货币名称',
        sortable: 'custom',
        formFieldItemType: 'input',
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'rate',
        label: '人民币汇率',
        sortable: 'custom',
        formFieldItemType: 'number',
    },
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
    },
]);
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);
const createActionName = ref('货币增加');
const updateActionName = ref('货币修改');

const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    // console.log('参数', paramData);

    const req = new Request('货币查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    onRefresh();
    tableHeight.value =
        window.innerHeight - tableMaxHeightAdjust;
    // alert(tableHeight.value);
    
});
const add = () => {
    initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    Object.assign(paramData, row, { primary_cod: row['currency_cod'] });
    dialogUpdateVisible.value = true;
};
const onAdded = (data: CurrencyModel) => {
    tableData.value.unshift(data);
    appStore.initData();
};
const onUpdated = (data: CurrencyModel) => {
    const i = findIndex(tableData.value, (o: CurrencyModel) => {
        return o.currency_cod === data.primary_cod;
    });
    console.log('data', data);
    console.log('i', i);
    
    if (i > -1) {
        Object.assign(tableData.value[i], data);
        appStore.initData();
    } else {
        ElMessage.error('修改失败');
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};

const onDelete = async () => {
    const rows: Array<CurrencyModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<string>();
    const labels = Array<string>();
    forEach(rows, (v: CurrencyModel) => {
        ids.push(v.currency_cod as string);
        labels.push(v.currency_nam as string);
    });

    const msg = labels.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下货币', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('货币删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: CurrencyModel, i: number) => {
                if (includes(ids, v.currency_cod)) {
                    tableData.value.splice(i, 1);
                }
            });
            appStore.initData();
        }
    }
};
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
